<template>
  <a-modal
    :title="$t('Child-user')+$t('Operate')"
    v-model="screate"
    @cancel="cancelhandle"
    width="60%"
    @ok="subnew"
    :cancelText="$t('Cancel')" 
		:okText="$t('Sure')" 
    :maskClosable="false"
    v-dragModal
  >
    <a-table :columns="columns" :dataSource="subdata" bordered :pagination='pagination' size='small' :locale="defaultSetting">
      <!-- 编辑子用户 -->
      <template
        v-for="col in ['permissions']"
        :slot="col"
        slot-scope="text, record, index">
        <div :key="col">
          <a-select
            :defaultValue="text"
            style="width: 120px"
            v-if="record.editable"
            @change="e => handleChange(e,record,col)">
            <a-select-option :value="item.value" :key="index" v-for="(item,index) in perdata">{{item.text}}</a-select-option>
          </a-select>
          <template v-else>
            <!-- {{text}} -->
            <span v-if="text=='full-control'">{{$t('Full_control')}}</span>
            <span v-else-if="text=='read'">{{$t('Read_only2')}}</span>
            <span v-else-if="text=='write'">{{$t('Write_only')}}</span>
            <span v-else-if="text=='read-write'">{{$t('Read_and_write2')}}</span>
          </template>
        </div>
      </template>
      <template slot="operation" slot-scope="text, record, index">
        <div class="editable-row-operations">
          <span v-if="record.editable">
            <a @click="() => save(record)">{{$t('Save')}} | </a>
            <a-popconfirm :title="$t('Sure-cancel-tip')" 
                          :ok-text="$t('Sure')" 
                          :cancel-text="$t('Cancel')"
                          @confirm="() => cancel(record.key)">
              <a>{{$t('Cancel')}}</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a @click="() => edit(record.id)">{{$t('Edit')}} | </a>
            <!-- 删除子用户 -->
            <a-popconfirm
              v-if="subdata.length"
              :title="$t('Sure-del-tip')"
              :ok-text="$t('Sure')" 
              :cancel-text="$t('Cancel')"
              @confirm="() => onDelete(record)"
            >
              <a href="javascript:;">{{$t('Delete')}}</a>
            </a-popconfirm>
          </span>
        </div>
      </template>
    </a-table>
    <a-button class="editable-add-btn" @click="handleAdd">{{$t('Add')}}{{$t('Child-user')}}</a-button>
    <div id="components-form-demo-advanced-search" v-if="flag">
      <a-spin size="large" style="position:absolute;left:50%; top:50%; transform: translate(-50%, -50%);z-index:1;background:rgba(255,255,255,.6);padding:10%" tip="Submit successfully Loading..." v-if="spinning == true"></a-spin>
      <a-form :form="form" class="ant-advanced-search-form">
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item :label="this.$t('User')+this.$t('Name')" has-feedback>
              <a-input
                v-decorator="['user',{
                        rules:[{required:true,message:$t('Enter')+$t('User')+$t('Name')},{pattern:namePattern,message:$t('Not_enter_special_characters')}],
                        initialValue:tarname.user_id
                    }]" disabled :placeholder="$t('Enter')+$t('User')+$t('Name')"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item :label="this.$t('Child-user')+this.$t('Name')" has-feedback>
              <a-input
                v-decorator="['id',{
                        rules:[{required:true,message:$t('Enter')+$t('Child-user')+$t('Name')},
                        {pattern:/^[a-zA-Z][a-zA-Z0-9_-]{2,31}$/,message: $t('Not_enter_special_characters6')}]
                    }]" :placeholder="$t('Enter')+$t('Child-user')+$t('Name')"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8" id='subuser_permissions'>
            <a-form-item :label="$t('Permission')" has-feedback > 
              <a-select  
                v-decorator="['permissions',{
	                    rules:[{required:true,message:$t('Choose')+$t('Permission')}]
                  }]" :placeholder="$t('Choose')+$t('Permission')">
                <a-select-option :value="item.value" :key="index" v-for="(item,index) in perdata">{{item.text}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" :style="{ textAlign: 'right' }">
            <a-button type="primary" @click="sureadd">{{$t('Add')}}</a-button>
            <a-button type="default" :style="{ marginLeft: '8px' }" @click="handleReset">{{$t('Clear')}}</a-button>
            <!-- <a :style="{ marginLeft: '8px', fontSize: '12px' }" @click="flag=false">{{$t('Finished')}}</a> -->
          </a-col>
        </a-row>
      </a-form>
    </div>
  </a-modal>
</template>

<script>
// const subdata = []
// var cacheData = []
import EmptyData from '@/components/common/EmptyData'
import request from '@/request/request'

export default {
  props: ["ss", "tarname"],
  components: { EmptyData },
  data() {
    return {
      form: this.$form.createForm(this),
      formlayout: {
        labelCol: { span: 7 },
        wrapperCol: { span: 17 }
      },
      screate: false,
      subdata : [],
      columns: [
        // {
        //   title: this.$t('User'),
        //   dataIndex: "user",
        //   key: "user",
        //   width: "20%",
        //   scopedSlots: { customRender: "user" }
        // },
        {
          title: "id",
          dataIndex: "id",
          key: "id",
          width: "20%",
          scopedSlots: { customRender: "id" }
        },
        {
          title: this.$t('Permission'),
          dataIndex: "permissions",
          key: "permissions",
          width: "30%",
          scopedSlots: { customRender: "permissions" }
        },
        {
          title: this.$t('Operate'),
          dataIndex: "operation",
          key: "operation",
          scopedSlots: { customRender: "operation" }
        }
      ],
      pagination:{
        defaultPageSize:5,
        showTotal: total => `${this.$t('A-total-of')} ${total} ${this.$t('Data')}`,
        showSizeChanger:true,
        pageSizeOptions: ['5', '15', '20', '25'],
        onShowSizeChange:(current, pageSize)=>this.pageSize = pageSize,
        buildOptionText: (props) => `${props.value} / ${this.$t('page')}`
      },
      uint: [
        { val: "KiB", label: "KiB" },
        { val: "MiB", label: "MiB" },
        { val: "GiB", label: "GiB" },
        { val: "TiB", label: "TiB" }
      ],
      // perdata: ["read", "write", "read-write", "full-control"],
      perdata: [
        { text:this.$t('Read_only2'), value:"read" },
        { text:this.$t('Write_only'), value:"write" },
        { text:this.$t('Read_and_write2'), value:"read-write" },
        { text:this.$t('Full_control'), value:"full-control" }
      ],
      flag: false,
      spinning:false,
      defaultSetting: { emptyText:<EmptyData /> }
    };
  },
  watch: {
    ss(val) {
      this.screate = val;
    },
    tarname(val) {
      for (const item of val.subusers) {
        // item.user = val.name;
        item.user = val.user_id;
      }
      this.subdata = val.subusers;
      localStorage.setItem('sub',JSON.stringify(val.subusers))
    },
    getlanguage(val){
			this.columns=[
				// { title: this.$t('User'),dataIndex: "user",key: "user",width: "20%",scopedSlots: { customRender: "user" } },
        { title: "id",dataIndex: "id",key: "id",width: "20%",scopedSlots: { customRender: "id" } },
        { title: this.$t('Permission'),dataIndex: "permissions",key: "permissions",width: "30%",scopedSlots: { customRender: "permissions" } },
        { title: this.$t('Operate'),dataIndex: "operation",key: "operation",scopedSlots: { customRender: "operation" } }
			];
      this.perdata = [
        { text:this.$t('Read_only2'), value:"read" },
        { text:this.$t('Write_only'), value:"write" },
        { text:this.$t('Read_and_write2'), value:"read-write" },
        { text:this.$t('Full_control'), value:"full-control" }
      ];
		}
  },
  computed: {
    getlanguage(){
			return this.$store.state.language
		}
  },
  methods: {
    getsubdata(){
      request('get', 'rgw/user/subuser',{
        // params:{
          // user:this.tarname.name
          user:this.tarname.user_id
        // }
      }).then(res=>{
        if(res.data.flag == 1) {
					this.model(res.data.id) //返回模板
					this.notice(res.data.id,res.data.params,res.data.flag) //通知列表显示
				}else {
          for (const item of res.data) {
            // item.user = this.tarname.name;
            item.user = this.tarname.user_id;
            item.id = this.tarname.user_id + ':' + item.subname;
          }
          this.subdata = res.data
          localStorage.setItem('sub',JSON.stringify(this.subdata))
        }
      })

    },
    cancelhandle(e) {
      this.form.resetFields();
      this.spinning=false
      // this.screate = false;
      this.flag = false;
      this.$emit("omodal", false, true);
    },
    subnew(e) {
      // e.preventDefault();
      // this.form.validateFields((err, value) => {
      //   if (!err) {
          // this.model(res.data.id) //返回模板
          // this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
					// this.gettask()  //任务栏信息
          this.form.resetFields();
          // this.screate = false;
          this.$emit("omodal", false, false);
          this.flag = false;
      //   }
      // });
    },
    handleAdd() {
      this.flag = true;
    },
    sureadd(e) {
      e.preventDefault();
      this.form.validateFields((err, value) => {
        if (!err) {
          this.spinning = true
          request('put', "rgw/user/subuser/", value)
            .then(res => {
              this.model(res.data.id) //返回模板
              this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
						  // this.gettask()  //任务栏信息
              this.form.resetFields();
              this.spinning = false
              this.getsubdata() //刷新数据
            }).catch(err => {
              this.spinning = false
            })
        }
      });
    },
    handleReset() {
      this.form.resetFields();
    },
    onDelete(key) {
      request('DELETE', "rgw/user/subuser",
        // data: key
        key
      )
      .then(res => {
        this.model(res.data.id) //返回模板
        this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
				// this.gettask()  //任务栏信息
        if (res.data.flag == 0) {
          const newData = [...this.subdata];
          this.subdata = newData.filter(item => item !== key);
        }
      });
    },
    handleChange(value, key, column) {
      const newData = [...this.subdata];
      const target = newData.filter(item => key === item)[0];
      if (target) {
        target[column] = value;
        this.subdata = newData;
      }
    },

    edit(key) {
      const newData = [...this.subdata];
      const target = newData.filter(item => key === item.id)[0];
      if (target) {
        target.editable = true;
        this.subdata = newData;
      }
    },
    save(key) {
      const newData = [...this.subdata];
      const target = key;
      if (target) {
        delete target.editable;
        // this.subdata = newData;
        // this.$axios.put(this.allurl + "rgw/user/subuser", target).then(res => {
        request('post', "rgw/user/subuser/update", target).then(res => {
          if (res.data.flag == 0) {
            this.subdata = newData;
          } else {
            this.subdata = JSON.parse(localStorage.getItem('sub'));
          }
          this.model(res.data.id) //返回模板
          this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
					// this.gettask()  //任务栏信息
        });
      }
    },
    cancel(key) {
      // const data = this.subdata
      const newData = [...this.subdata];
      const target = newData.filter(item => key === item.key)[0];
      if (target) {
        Object.assign(
          target,
        );
        delete target.editable;
        this.subdata = JSON.parse(localStorage.getItem('sub'));  //确保取消后恢复原数据
      }
    },
  }
};
</script>

<style scoped>

.ant-select {
  width: 100% !important;
}
.client {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}
.subtn {
  margin-right: 1em;
  margin-top: 0.3em;
}
.add {
  overflow: hidden;
  border: 3px solid #e6f4ff;
  padding-top: 1em;
}
.ant-form-item-label {
  /*width: 35% !important;*/
}
.ant-advanced-search-form {
  padding: 24px;
  background: #fbfbfb;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
}

.ant-advanced-search-form .ant-form-item {
  display: flex;
}

.ant-advanced-search-form .ant-form-item-control-wrapper {
  flex: 1;
}

#components-form-demo-advanced-search .ant-form {
  max-width: none;
}

#components-form-demo-advanced-search .search-result-list {
  margin-top: 16px;
  border: 1px dashed #e9e9e9;
  border-radius: 6px;
  background-color: #fafafa;
  min-height: 200px;
  text-align: center;
  padding-top: 80px;
}

</style>
